package com.hao.controller;

import com.hao.dto.DataUploadRequest;
import com.hao.service.SensorDataService;
import com.hao.util.DataValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 传感器数据控制器
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class SensorDataController {
    
    @Autowired
    private SensorDataService sensorDataService;
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "服务运行正常");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
    
    /**
     * 数据上传接口
     */
    @PostMapping("/data")
    public Map<String, Object> uploadData(@RequestBody DataUploadRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> dataList = request.getData();
            if (dataList == null || dataList.isEmpty()) {
                result.put("code", 400);
                result.put("message", "数据列表不能为空");
                return result;
            }
            
            // 验证数据
            String validationResult = DataValidator.validateDataList(dataList);
            if (!"valid".equals(validationResult)) {
                result.put("code", 400);
                result.put("message", validationResult);
                return result;
            }
            
            // 保存数据
            int savedCount = sensorDataService.batchSave(dataList);
            
            result.put("code", 200);
            result.put("message", "数据保存成功");
            result.put("savedCount", savedCount);
            
            log.info("成功保存{}条传感器数据", savedCount);
            
        } catch (Exception e) {
            log.error("保存传感器数据时发生异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "服务器内部错误");
        }
        
        return result;
    }
} 